import argparse

def check_devices(devices:list):
    '''
    @param devices: a list of device id
    @return: bool value indicating whether the devices list is ok
    '''
    if len(devices) not in [1,2,4,8]:
        raise Exception("Only support devices with number = 1, 2, 4 or 8")
    if len(set(devices)) != len(devices):
        raise Exception("Unique id required")
    devices.sort()
    a = min(devices)
    b = max(devices)
    if b - a != len(devices)-1:
        raise Exception("Ids must be successive")
    if len(devices) <= 4:
        if a<=3 and b>=4:
            raise Exception("Ids should be in one sub-net")
    return True

def dump_to_file(cmds:list):
    with open("run_pro.sh",'w') as f:
        f.write('\n'.join(cmds))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="the script used to generate run shell")
    parser.add_argument('--device', type=str, default='0,1,2,3,4,5,6,7', help='the device id of the devices to use')
    parser.add_argument('--no_run', type=bool, default=False, help='')
    args_opt, unknown = parser.parse_known_args()
    devices = args_opt.device
    no_run = args_opt.no_run
    devices = devices.split(',')
    devices = list(map(lambda x:int(x),devices))
    check_devices(devices)
    device_start = min(devices)
    cmds = []
    cmds.append(f"python ge_table.py --device {','.join(list(map(lambda x:str(x),devices)))}")
    cmds.append(f"bash run.sh {len(devices)} {device_start}")
    dump_to_file(cmds)
    if no_run == False:
        import os
        os.system("bash ./run_pro.sh")
    